package org.example.controller.userController;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.common.Result;
import org.example.controller.request.*;
import org.example.entity.*;
import org.example.exception.ServiceException;
import org.example.service.*;
import org.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/project")
public class ProjectController {
    @Autowired
    private ProjectReviewService projectReviewService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectTypeService projectTypeService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserProjectService userProjectService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private PlanService planService;
    @Autowired
    private ProblemService problemService;
    @Autowired
    private ResourceTypeService resourceTypeService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private FeedbackAcceptanceService feedbackAcceptanceService;
    @Autowired
    private ClasstypeService classtypeService;
    //项目申请
    @PostMapping("/application")
    public Result application(@RequestBody ProjectRequest projectRequest){
//        projectsService.add(projectRequest);
        Project projectss = projectService.selectprijectname((projectRequest.getProjectName()));
        if (projectss != null) {
            // 抛出一个自定义的异常
            return Result.error("项目名已存在");    //项目查重校验
        }
        Project project=new Project();
        project.setProjectName(projectRequest.getProjectName());
        project.setProjectOverview(projectRequest.getProjectOverview());
        project.setProjectType(projectRequest.getProjectType());
        project.setState("0");
        project.setBusinessPlan(projectRequest.getBusinessPlan());
        project.setTeamIntroduction(projectRequest.getTeamIntroduction());
        project.setContactEmail(projectRequest.getContactEmail());
        project.setSupervisor(projectRequest.getSupervisor());
        project.setReviewer(projectRequest.getReviewer());
        project.setBusinessPlan(projectRequest.getBusinessPlan());
        project.setUsername(TokenUtils.getCurrentUser().getName());
        project.setGitRepo(projectRequest.getGitRepo());
        project.setReview("待评审");
        projectService.save(project);
      projectRequest.getTeammates();
        //将所有队员与项目关联
        List<String> list = new ArrayList<>();
        for (String teammate : projectRequest.getTeammates()) {

           list.add(userService.selectbyId(Integer.valueOf(teammate)));
        }
        //队员关联
        for (String s : list) {
            UserProject userProject=new UserProject();
            userProject.setProjectName(projectRequest.getProjectName());
            userProject.setStates("0");
            userProject.setUserName(s);
            userProject.setPrivilege(0);
            userProjectService.save(userProject);
        }
        //队长关联
        UserProject userProject2=new UserProject();
        userProject2.setProjectName(projectRequest.getProjectName());
        userProject2.setStates("审核中");
        userProject2.setPrivilege(1);   //负责人权限
        userProject2.setUserName(TokenUtils.getCurrentUser().getName());
        userProjectService.save(userProject2);
        //老师关联
        UserProject userProject3=new UserProject();
        userProject3.setProjectName(projectRequest.getProjectName());
        userProject3.setStates("审核中");
        userProject3.setPrivilege(3);
        userProject3.setUserName(projectRequest.getSupervisor());
        userProjectService.save(userProject3);
        //审核专家关联
        UserProject userProject4=new UserProject();
        userProject4.setProjectName(projectRequest.getProjectName());
        userProject4.setStates("审核中");
        userProject4.setPrivilege(3);
        userProject4.setUserName(projectRequest.getReviewer());
        userProjectService.save(userProject4);
    return Result.success();
    }



    //文件上传
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        // 处理文件逻辑
        String fileUrl = fileService.upload(file);
        return Result.success(fileUrl);
    }
    //共享社区文件上传
    @PostMapping("/addFile")
    public Result addFile(@RequestBody FileRequest fileRequest){
        FeedbackAcceptance feedbackAcceptance=new FeedbackAcceptance();
        feedbackAcceptance.setDescription(fileRequest.getDescription());
        feedbackAcceptance.setTitle(fileRequest.getTitle());
        feedbackAcceptance.setThumbnail(fileRequest.getType());
        feedbackAcceptance.setUrl(fileRequest.getUrl());
        feedbackAcceptance.setUsername(TokenUtils.getCurrentUser().getUsername());
        // 获取当前日期和时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);
        feedbackAcceptance.setDate(formattedTime);
        feedbackAcceptance.setType(fileRequest.getType());

        feedbackAcceptanceService.save(feedbackAcceptance);

        return Result.success();
    }
    //资源申请
    @PostMapping("/resources")
    public Result sq(@RequestBody ResourceRequest resourceRequest){
        Resources resources=new Resources();
        resources.setOpinion(null);
        resources.setResourcesType(resourceRequest.getResourceType());
        resources.setStates("0");
        resources.setUsername(TokenUtils.getCurrentUser().getName());
        resources.setDescribes(resourceRequest.getDescription());
        resources.setProjectName(resourceRequest.getProject());
        if(resourceRequest.getResourceType()!="资金"){
            resources.setAmount(0);
        }else {
            resources.setAmount(resourceRequest.getAmount());
        }
        resourceService.save(resources);

        return Result.success();
    }
    //指导老师查询
    @GetMapping("/selectSupervisor")
    public Result selectSupervisor(){
        String role="指导老师";
        List<User> userList=userService.selectRole(role);

        return Result.success(userList);
    }
    //班级名字查询
    @GetMapping("/classList")
    public Result classList(){
        List<ClassType> classTypeList = classtypeService.list(new QueryWrapper<ClassType>().orderByAsc("id"));

        return Result.success(classTypeList);
    }
    //班级查询
    @GetMapping("/selectClasses")
    public Result selectClasses(){
        List<ClassType> classTypeList = classtypeService.list(new QueryWrapper<ClassType>().orderByAsc("id"));
        return Result.success(classTypeList);
    }
    //班级学生查询
    @GetMapping("/selectStudents")
    public Result selectStudents(@RequestParam String className){

        List<User> userList=userService.selectbyclassname(className,TokenUtils.getCurrentUser().getName());
        return Result.success(userList);
    }
    //用户头像查询
    @GetMapping("/getAvatarUrl")
    public Result getAvatarUrl(@RequestParam String username){

        List<User> userList=userService.AvatarUrl(username);
        return Result.success(userList);
    }

    //评审专家查询
    @GetMapping("/selectReviewerOptions")
    public Result selectReviewerOptions(){
        String role="评审专家";
        List<User> userList=userService.selectRole(role);

        return Result.success(userList);
    }
    //项目类型查询
    @GetMapping("/selectProjectType")
    public Result selectProjectType(){
        List<Projecttype> projecttypeList = projectTypeService.list(new QueryWrapper<Projecttype>().orderByAsc("id"));

        return Result.success(projecttypeList);


    }
    //文件共享社区查询
    @GetMapping("/selectFeedbackAcceptance")
    public Result selectFeedbackAcceptance(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
        Page<FeedbackAcceptance> page = new Page<>(pageNum, pageSize);
        QueryWrapper<FeedbackAcceptance> wrapper = new QueryWrapper<FeedbackAcceptance>().orderByAsc("id");

// 执行分页查询（同时包含分页参数和排序条件）
        feedbackAcceptanceService.page(page, wrapper);


        return Result.success(page);


    }
    //队员查询
    @GetMapping("/selectprojectstudent")
    public Result selectprojectstudent(@RequestParam("projectName") String projectName){
        List<UserProject> userProjectList=userProjectService.selectprojectstudent(projectName);
        return Result.success(userProjectList);
    }
    @GetMapping("/qx")
    public Result qx(@RequestParam("projectName") String projectName){
        List<UserProject> userProjectList=userProjectService.selectprojectstudentss(projectName,TokenUtils.getCurrentUser().getName());
        return Result.success(userProjectList);
    }
    //本人项目查询
    @GetMapping("/selectUserProject")
    public Result selectUserProject(){
        List<UserProject> userProjectList=userProjectService.selectUserProject(TokenUtils.getCurrentUser().getName());
        return Result.success(userProjectList);
    }
    //本人申请项目查询
    @GetMapping("/card")
    public Result card(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
        Page<Project> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Project> wrapper = new QueryWrapper<Project>().eq("username",TokenUtils.getCurrentUser().getName()).orderByAsc("id");

// 执行分页查询（同时包含分页参数和排序条件）
        projectService.page(page, wrapper);

        return Result.success(page);
    }
    //指导老师项目查询
    @GetMapping("/selectList")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,

                               @RequestParam String projectName){
        QueryWrapper<Project> queryWrapper = new QueryWrapper<Project>().orderByDesc("id");
//        queryWrapper.like("username" ,TokenUtils.getCurrentUser().getName());
        queryWrapper.like("project_name" ,projectName);
        queryWrapper.eq("supervisor",TokenUtils.getCurrentUser().getName());
        // select *from user where username like '%#{username}%' and name like '%#{name}%'
        Page<Project> page = new Page<>(pageNum, pageSize); // 显式声明泛型
        Page<Project> resultPage = projectService.page(page, queryWrapper);
        List<Project> projectList=projectService.selectProject(TokenUtils.getCurrentUser().getUsername());
        return Result.success(resultPage);
    }
    //本人申请资源申请查询
    @GetMapping("/selectResource")
    public Result selectResource(){
        List<Resources> resources=resourceService.selectResource(TokenUtils.getCurrentUser().getName());
        return Result.success(resources);
    }

    //进程查询
    @GetMapping("/selectCurrentProjectData")
    public Result selectCurrentProjectData(@RequestParam("projectName") String projectName){
        CurrentProjectData currentProjectData = new CurrentProjectData();
        currentProjectData.setTasks(taskService.selectTask(projectName));
        currentProjectData.setNextSteps(planService.selectPlan(projectName));
        currentProjectData.setIssues(problemService.selectProblem(projectName));

        return Result.success(currentProjectData);
    }
    @PostMapping("/updateTaskStatus")
    public Result updateTaskStatus(@RequestParam("id") int id,@RequestBody Map<String, Boolean> requestBody){
        Boolean completed = requestBody.get("completed");
        taskService.updateTaskStatus(id,completed);
        return Result.success();
    }
    @PostMapping("/tg")
    public Result tg(@RequestBody Project project){
        userProjectService.updatestate(project.getProjectName());
       projectService.updatstate(project.getProjectName(),project.getState());
        return Result.success();
    }
    //资源类型查询
    @GetMapping("/selectResourcesType")
    public Result selectResourcesType(){
        List<ResourceType> resourceTypeList = resourceTypeService.list(new QueryWrapper<ResourceType>().orderByAsc("id"));
        return Result.success(resourceTypeList);
    }
//    //任务查询
//    @GetMapping("/selectTask")
//    public Result selectTask(@RequestBody){
//
//        return Result.success();
//    }
    //任务添加
    @PostMapping("/addTask")
    public Result addTask(@RequestParam("selectedMembers") String selectedMembers,@RequestBody AddRequest addRequest ){
        Task task=new Task();
        task.setResponsibleName(selectedMembers);
        task.setProjectName(addRequest.getProject());
        task.setTask(addRequest.getContent());
        task.setCompleted(false);
         taskService.save(task);
        return Result.success();
    }
    //删除任务
    @PostMapping("/removeTask")
    public Result removeTask( @RequestParam("id") int id){
        taskService.removeById(id);
        return Result.success();
    }
    //删除计划
    @PostMapping("/removePlan")
    public Result removePlan( @RequestParam("id") int id){
        planService.removeById(id);
        return Result.success();
    }
    //删除问题
    @PostMapping("/removeProblem")
    public Result removeProblem( @RequestParam("id") int id){
        problemService.removeById(id);
        return Result.success();
    }
//    //计划查询
//    @GetMapping("/selectPlan")
//    public Result selectPlan(@RequestBody){
//
//        return Result.success();
//    }
    //计划添加
    @PostMapping("/addPlan")
    public Result addPlan(@RequestBody AddRequest addRequest){
        Plan plan=new Plan();
        plan.setPlan(addRequest.getContent());
        plan.setProjectName(addRequest.getProject());
        // 获取当前日期和时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);
        plan.setCreateTime(formattedTime);
        planService.save(plan);

        return Result.success();
    }
//    //问题查询
//    @GetMapping("/selectProblem")
//    public Result selectProblem(@RequestBody){
//
//        return Result.success();
//    }
    //问题添加
    @PostMapping("/addProblem")
    public Result addProblem(@RequestBody AddRequest addRequest ){
        Problem problem=new Problem();
        problem.setProblem(addRequest.getContent());

        // 获取当前日期和时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);
        problem.setCreateTime(formattedTime);
        problem.setProjectName(addRequest.getProject());
        problemService.save(problem);
        return Result.success();
    }
    @GetMapping("/reviewResult")
    public Result reviewResult(@RequestParam Integer pageNum, @RequestParam Integer pageSize){


// 执行分页查询（同时包含分页参数和排序条件）
        Page<ProjectReview> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ProjectReview> wrapper = new QueryWrapper<ProjectReview>().eq("username", TokenUtils.getCurrentUser().getName()).orderByAsc("id");

// 执行分页查询（同时包含分页参数和排序条件）
        projectReviewService.page(page, wrapper);
        return Result.success(page);
    }

}
